package net.quanter.sketch;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/***
 *
 * 2020-07-14
 * @author harley-dog
 *
 */
public class SvgParser {

    public static List<Point> parse(InputStream input) throws DocumentException {
        //1.创建Reader对象
        SAXReader reader = new SAXReader();
        //2.加载xml
        Document document = null;
        document = reader.read(input);
        //3.获取根节点
        Element rootElement = document.getRootElement();
        List<Point> pointList = new ArrayList<>();
        // 找到所以text类型的坐标点
        findPoints(rootElement, pointList);
        return pointList;
    }

    private static void findPoints(Element rootElement, List<Point> pointList) {
        String eleName = rootElement.getName();
        if ("text".equalsIgnoreCase(eleName)) {
            Element stuChild = rootElement.elementIterator().next();
            String id = rootElement.attributeValue("id").trim();
            if (id!=null && id.startsWith("$")) {
                int x = Integer.parseInt(stuChild.attributeValue("x").trim());
                int y = Integer.parseInt(stuChild.attributeValue("y").trim());
                pointList.add(new Point(id.replaceFirst("\\$",""), x, y));
            }
        }
        Iterator iterator = rootElement.elementIterator();
        while (iterator.hasNext()) {
            Element element = (Element)iterator.next();
            findPoints(element, pointList);
        }
    }
}
